<template>
  <view class="container">
    <!-- 商品信息区域 -->
    <view class="product-section">
      <image class="product-image" v-if="goodInfo.packageCoverImage" :src="goodInfo.packageCoverImage" mode="aspectFill"></image>
	   <image class="product-image" v-else src="/static/img/icon_haibao.png" mode="aspectFill"></image>
      <view class="product-info">
        <view class="product-name">{{goodInfo.name}}</view>
		<view class="specs">商品规格：{{goodInfo.specs}}</view>
        <view class="price-section">
          <text class="discount-price">¥{{goodInfo.currentPrice}}</text>
          <text class="original-price">¥{{goodInfo.originalPrice}}</text>
        </view>
      </view>
    </view>

    <!-- 数量与总价模块 -->
    <view class="quantity-total-section">
      <view class="section-item">
        <text class="item-label">数量</text>
        <text class="item-value">1</text>
      </view>
      <view class="section-item">
        <text class="item-label">总价</text>
		<text class="item-value total-price">¥{{totalPrice}}</text>
       <!-- <text class="item-value total-price">¥{{goodInfo.currentPrice}}</text> -->
      </view>
	  <view class="section-item" v-if="goodInfo.admJianNum&&goodInfo.admJianNum!='0.0'">
	    <text class="item-label">商家优惠</text>
	    <text class="item-value total-price">¥{{goodInfo.admJianNum}}</text>
	  </view>
	  
    </view>
    
	<view class="youhuiLine" v-if="couponList.length==0">
		<view class="yhTitle">优惠券</view>
		<view class="coupon">
			<span>暂无优惠券</span>
			<!-- <image src="/static/img/icon_arrow_right.png" mode="" class="jtImg"></image> -->
		</view>
	</view>
	<view class="youhuiLine" v-if="couponList.length>0">
		<view class="yhTitle">
			<checkbox-group @change="toggleCoinDeduction">
				<label class="uni-list-cell uni-list-cell-pd" >
					<view>
						<checkbox :checked="conponCk" value="1"/>优惠券
					</view>
					<view></view>
				</label>
			</checkbox-group>
			<!-- <checkbox  @change="toggleCoinDeduction" color="#FF2442"/> -->
			
		</view>
		<view class="coupon">
			<span style="color: red;">-￥{{coupon.amount}}</span>
			<!-- <image src="/static/img/icon_arrow_right.png" mode="" class="jtImg"></image> -->
		</view>
	</view>
	
    <!-- 金币抵扣 -->
    <view class="coin-deduction">
      <label class="checkbox">
		  <checkbox-group @change="goldcheckbox">
		  	<label class="uni-list-cell uni-list-cell-pd" >
		  		<view>
		  			<checkbox :checked="goldCoiCk" value="1"/>
					<text>使用金币抵扣 (可用金币: {{goldCoin}}，可抵扣¥{{goldCoinNum}})</text>
		  		</view>
		  		<view></view>
		  	</label>
		  </checkbox-group>
      <!--  <checkbox :checked="useCoins" @change="" color="#FF2442"/> -->
        
      </label>
    </view>
	<!-- <view class="youhuiLine">
		<view class="yhTitle">金币抵扣2元</view>
		<view class="yhright">
			<checkbox-group>
				<label>
					<checkbox value="cb" :checked="true" />
				</label>
			</checkbox-group>
		</view>
	</view> -->
	<view class="Appointment" style="margin-top: 20rpx;" v-if="goodInfo.isAppointment">
		<view class="youhuiLine" style="margin: 0;border-bottom: 1px solid #eaeaea;" @click="goShop">
			<view class="yhTitle">预约门店</view>
			<view class="coupon">
				<span>{{ckshop.storeName}}</span>
				 <image src="/static/img/icon_arrow_right.png" mode="" class="jtImg"></image>
			</view>
		</view>
		<view class="youhuiLine" style="margin: 0;">
			<view class="yhTitle">预约时间</view>
			<picker mode="date" @change="bindStartDateChange" :start="newDate">
			<view class="coupon">
				<span>{{makeTime?makeTime:'点击选择预约时间'}}</span>
				 <image src="/static/img/icon_arrow_right.png" mode="" class="jtImg"></image>
			</view>
			</picker>
		</view>
		<view class="youhuiLine" style="margin: 0;border-bottom: 1px solid #eaeaea;" v-if="goodInfo.productCategory==25">
			<view class="yhTitle">姓名</view>
			<view class="coupon">
				<input type="text" v-model="makeName" placeholder="请输入" class="yueyueINput"/>
			</view>
		</view>
		<view class="youhuiLine" style="margin: 0;border-bottom: 1px solid #eaeaea;" v-if="goodInfo.productCategory==25">
			<view class="yhTitle">电话</view>
			<view class="coupon">
				<input type="number" v-model="makePhone"  placeholder="请输入" class="yueyueINput"/>
			</view>
		</view>
		<view class="youhuiLine" style="margin: 0;border-bottom: 1px solid #eaeaea;" v-if="goodInfo.productCategory==25">
			<view class="yhTitle">身份证号</view>
			<view class="coupon">
				<input type="number" v-model="makeIdCard"  placeholder="请输入" class="yueyueINput"/>
			</view>
		</view>
		
	</view>
	
	
	<view class="detailsBox">
		<view class="descriptionTitle">购买须知</view>
		 <rich-text :nodes="goodInfo.purchaseNotes" style="background: #fff;"></rich-text>
		 <view>
			
		<!-- <view class="descriptionTitle" style="margin-top: 20rpx;">购买规则</view>
		<view class="guizhems" style="padding-bottom: 20rpx;">遵循时间优先原则，每位用户均可参与砍价，餐品价格会随砍价逐渐降低，且用户可随时下单购买，先下单者获得餐品。
特别提示：每个套餐每人每天仅可砍价 1 次，每晚 12 点套餐恢复原价。</view> -->
			 	
			 <checkbox-group @change="changeNotescheckbox">
			 	<label class="uni-list-cell uni-list-cell-pd" >
			 		<view>
			 			<checkbox :checked="ckpurchaseNotes" value="1"/>
			 					<text>请先仔细阅读并先勾选购买须知</text>
			 		</view>
			 		<view></view>
			 	</label>
			 </checkbox-group>
			  
		 </view>
	</view>

    <!-- 底部支付菜单 -->
    <view class="fixed-bottom-menu">
      <view class="price-display">
        <text class="final-price">¥{{newPrice}}</text>
        <text class="original-price-line">¥{{goodInfo.originalPrice}}</text>
      </view>
      <view class="pay-button" @click="confirmPayment">
        <text>确认支付</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      quantity: 1,
      discountPrice: 3999,
      originalPrice: 4999,
      useCoins: false,
      coinDeduction: 20,
	  id:'',
	  goodInfo:'',
	  ckpurchaseNotes:false,
	  openid:'',
	  orderId:'',
	  couponList:[],
	  coupon:'',
	  conponCk:false,
	  newPrice:'',
	  goldCoin:0,
	  goldCoinNum:'',
	  goldCoiCk:false,
	  shareId:'',
	  userInfo:'',
	  conponYj:'',
	  makeTime:'',
	  newDate:'',
	  ckshop:'',
	  totalPrice:'',
	  makeName:'',
	  makePhone:'',
	  makeIdCard:'',
	  isFalg:true,
    }
  },
  computed: {
    finalPrice() {
      return this.useCoins ? (this.discountPrice - this.coinDeduction) : this.discountPrice
    }
  },
  onLoad(opt) {
  	this.id=opt.id
	if(opt.shareId){
		this.shareId=opt.shareId
	}
	this.openid= uni.getStorageSync("openid")
	this.userInfo= uni.getStorageSync("userInfo")
	this.getData()
	
	 const today = new Date();
	 this.newDate=today.toISOString().split('T')[0]
	
  },
  onShow() {
  	this.ckshop= uni.getStorageSync("ckshop")
  },
  methods: {
	  goShop(){
		  uni.navigateTo({
		  	url:'shopList?type=1'
		  })
	  },
	  bindStartDateChange(e){
		  this.makeTime = e.detail.value
	  },
	  getGold(){
	    this.$http('jeecg-boot/app/market/bicGoldRecord/getTotalGoldKsyNumByUserId',{
	    	userId:this.userInfo.id,
			//userId:'1958543121398665218',
			status:1
	    },'GET').then(res => {
			  if(res.result){
				  this.goldCoin=res.result.totalGoldNum
				   this.jsgoldCoin()
			  }else{
				  this.goldCoinNum=0
			  } 
	    	 
	     })
	  },
	  jsgoldCoin(){
		  if(this.goldCoin>500){
			  this.goldCoinNum=5
		  }else{
			  this.goldCoinNum=this.goldCoin/100
		  }
		  var xianjia= this.goodInfo.currentPrice 
		  if(xianjia<11){
			   var jianNum=11 - xianjia
			   this.goldCoinNum=this.goldCoinNum-jianNum
		  }
		  if(xianjia<6){
		  			    this.goldCoinNum=0
		  }
		  this.goldCoinNum=this.goldCoinNum.toFixed(2)
		  this.conponYj=this.goldCoinNum
	  },
	 
	  getData(){
	  	uni.showLoading({
	  		title: '加载中'
	  	})
	  	this.$http('jeecg-boot/app/market/bicProduct/queryById',{
	  			   id:this.id
	  	},'POST').then(res => {
	  			   //console.log(res)
	  		 uni.hideLoading();
	  		 this.goodInfo=res.result
			 //this.goodInfo.currentPrice=
			 this.newPrice=this.goodInfo.currentPrice
			 this.totalPrice=this.goodInfo.currentPrice + this.goodInfo.admJianNum
			 this.totalPrice=this.totalPrice.toFixed(2)
			 this.getCouList()
			 this.getGold()
	  	 })
	  },
	  getCouList(){
		  this.$http('jeecg-boot/app/market/bicCoupon/list',{
		  		   pageNo:1,
		  		   pageSize:10,
		  		   useStatus:0,
				   currentAmount:this.goodInfo.currentPrice,
				   userId:this.userInfo.id
		  },'GET').then(res => {
		  		   //console.log(res)
		  		 var List=res.result.records
		  		 this.couponList=List
				 this.coupon=List[0]
		  	 //this.goodsList2=res.result.records
		   })
	  },
    toggleCoinDeduction(e) {
      // console.log(e)
	   //console.log(e.detail.value)
	   var values = e.detail.value;
	  // this.goodInfo.currentPrice=38.2
	   if(values.length){
		   this.conponCk=1
		  // debugger
		   var xianjia= this.goodInfo.currentPrice  - this.coupon.amount
		   if(xianjia<11){
			   var jianNum=11 - xianjia
			   this.goldCoinNum=this.goldCoinNum-jianNum
		   }
		   if(xianjia<6){
			    this.goldCoinNum=0
		   }
		   this.goldCoinNum= Number(this.goldCoinNum)
		  // console.log(this.goldCoinNum)
		   this.goldCoinNum=this.goldCoinNum.toFixed(2)
		  // if(this.goldCoinNum)
		   if(this.goldCoiCk){
			   this.newPrice= this.goodInfo.currentPrice  - this.coupon.amount - this.goldCoinNum
		   }else{
			   this.newPrice= this.goodInfo.currentPrice  - this.coupon.amount 
		   }
	   }else{
		   this.conponCk=false
		   this.goldCoinNum=this.conponYj
		   if(this.goldCoiCk){
		   		this.newPrice= this.goodInfo.currentPrice  - this.goldCoinNum
		   }else{
		   		this.newPrice= this.goodInfo.currentPrice 
		   }
	   }
	   /* if(values[0].includes(1)){
	   		this.conponCk=1
		}else{
			this.conponCk=false
		} */
		
		this.newPrice=this.newPrice.toFixed(2)
		if(this.newPrice<0.01){
			this.newPrice=0.01
		}
	   console.log(this.conponCk)
    },
	goldcheckbox(e){
	  var values = e.detail.value; 
	   if(values.length){
		   this.goldCoiCk=1
		   if(this.conponCk){
		    this.newPrice= this.goodInfo.currentPrice  - this.coupon.amount - this.goldCoinNum
		   }else{
		   	this.newPrice= this.goodInfo.currentPrice  - this.goldCoinNum
		   }
		  
	   }else{
	   	 this.goldCoiCk=false
		 if(this.conponCk){
		  this.newPrice= this.goodInfo.currentPrice  - this.coupon.amount
		 }else{
		 	this.newPrice= this.goodInfo.currentPrice
		 }
	   }
	   this.newPrice=this.newPrice.toFixed(2)
	  /* if(this.newPrice<1){
	   	this.newPrice=1
	   } */
	   if(this.newPrice<0.01){
	   	this.newPrice=0.01
	   }
	},
	changeNotescheckbox(e){
		var values = e.detail.value;
		 if(values.length){
			this.ckpurchaseNotes=true 
		 }else{
			this.ckpurchaseNotes=false
		 }
	},
    confirmPayment() {
	  if(this.goodInfo.type==1){
		  console.log(this.goodInfo.seckillEndTime)
		  const currentTime = new Date();
		  const targetTime = new Date(this.goodInfo.seckillEndTime); // 替换为目标时间点
		   
		  if (currentTime > targetTime) {
		    console.log('当前时间已超过目标时间点');
			uni.showToast({
			 title: '此商品秒杀时间已过期，请重新选择商品',
			 icon:'none',
			 duration: 3000
			});
			return false
		  } else {
		    console.log('当前时间未超过目标时间点');
		  }
	  }
	  if(!this.ckpurchaseNotes){
		  uni.showToast({
		      title:'请先仔细阅读并先勾选购买须知',
		  	   icon:'none',
		      duration: 3000,
		  })
		  return false
	  }
      uni.showLoading({
     	title: '加载中'
     })
	 if(this.conponCk){
	   var couponId=this.coupon.id
	   var couponAmount = this.coupon.amount
	 }else{
		 var couponId=''
		 var couponAmount = ''
	 }
	 if(this.goldCoiCk){
	 	var goldNum=this.goldCoinNum*100
	 }else{
	 	var goldNum = ''
	 }
	 goldNum:this.goldCoinNum
	  var makeTime=''
	  var makeStoreId=''
	  if(this.goodInfo.isAppointment){
		  if(this.makeTime){
		  		 makeTime=this.makeTime
		  		 makeStoreId=this.ckshop.storeId
		  }else{
			 uni.showToast({
			  title: '请选择预约时间',
			  icon:'none',
			  duration: 3000
			 });
			 return false 
		  }
		  if(this.goodInfo.productCategory==25){
		  		 if(!this.makeName){
		  			 uni.showToast({
		  			  title: '请填写预约姓名',
		  			  icon:'none',
		  			  duration: 3000
		  			 });
		  			 return false
		  		 }
		  		 if(!this.makePhone){
		  				 uni.showToast({
		  				  title: '请填写预约手机号',
		  				  icon:'none',
		  				  duration: 3000
		  				 });
		  				 return false
		  		 }else if(this.makePhone.length!=11){
					 uni.showToast({
					  title: '请正确填写手机号',
					  icon:'none',
					  duration: 3000
					 });
					 return false
				 }
		  		 if(!this.makeIdCard){
		  			 uni.showToast({
		  			  title: '请填写预约身份证号',
		  			  icon:'none',
		  			  duration: 3000
		  			 });
		  			 return false
		  		 }else if(this.makeIdCard.length!=18){
					 uni.showToast({
					  title: '请正确填写身份证号',
					  icon:'none',
					  duration: 3000
					 });
					 return false
				 }
		  		
		  }
	  }
	 if(!this.isFalg){
		 return false
	 }
	 this.isFalg=false
     this.$http('jeecg-boot/app/market/bicOrder/add',{
     	productId:this.id,
     	goldDeduct:0,
     	actualPay:this.goodInfo.currentPrice,
		sharePerson:this.shareId,
		couponId:couponId,
		couponAmount:couponAmount,
		goldNum:goldNum,
		makeTime:makeTime,
		makeStoreId:makeStoreId,
		makeName:this.makeName,
		makePhone:this.makePhone,
		makeIdCard:this.makeIdCard,
     },'POST').then(res => {
     	 
     	 uni.hideLoading();
     	 if(res.code==200){
			 this.orderId=res.result
     		   /* uni.showToast({
     		       title:'下单成功',
     		   	   icon:'none',
     		       duration: 3000,
     		   });
     		   uni.navigateTo({
     		   	url:'../user/orderList'
     		   }) */
			   this.wxpayFn()
     	 }else{
     		 uni.showToast({
     		     title:res.message,
     		 	 icon:'none',
     		     duration: 3000,
     		 });
     	 }
     	// this.goodInfo=res.result
      }).catch(err=>{
     	  this.isFalg=true
      })
     	  
      // 实际开发中这里应该是调用支付接口
    },
	wxpayFn(){
		this.$http('jeecg-boot/api/pay/wxPay',{
				   orderId:this.orderId,
				   openid:this.openid,
		},'POST').then(res => {
				   //console.log(res)
			 uni.hideLoading();
			 this.requestPayment(res.result.data)
			
		 })
	},
	requestPayment(data){
		var that=this;
		var payInfo=data;
		console.log(payInfo)
		uni.requestPayment({
			provider: 'wxpay',
			//timeStamp: String(Date.now()),
			timeStamp: payInfo.timeStamp,
			nonceStr: payInfo.nonceStr,
			package:payInfo.package,
			signType: payInfo.signType,
			paySign: payInfo.paySign,
			appid:payInfo.appid,	
			/* provider: 'wxpay',
			orderInfo:{
				"appid":payInfo.appid,  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
				"noncestr": payInfo.nonceStr, // 随机字符串
				 "package": "Sign=WXPay",         // 固定值
				"partnerid":payInfo.mchId,      // 微信支付商户号
				"prepayid": payInfo.prepayId, // 统一下单订单号 
				"timeStamp": String(Date.now()),      // 时间戳（单位：秒）
				"sign": payInfo.sign // 签名，这里用的 MD5/RSA 签名
			}, */
		    success: function (res) {
				 this.isFalg=true
		        console.log('success:' + JSON.stringify(res));
				 uni.showToast({
					 title: '支付成功',
					 icon:'none',
					 duration: 2000
				 });
				 uni.redirectTo({
				 	url:'../user/orderDetail?id='+that.orderId
				 })
				
		    },
		    fail: function (err) {
				 this.isFalg=true
			  console.log(err)
		      uni.showToast({
				 title: '支付失败',
				 icon:'none',
				 duration: 2000
		      });
			  uni.redirectTo({
			  	url:'../user/orderDetail?id='+that.orderId
			  })
			  
		    }
		}); 
	}
  }
}
</script>

<style>
page {
  background-color: #f5f5f5;
  padding-bottom: 100px; /* 为底部固定菜单留出空间 */
}

.container {
  padding: 20rpx;
}

/* 商品信息区域 */
.product-section {
  display: flex;
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.product-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 10rpx;
}

.product-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.price-section {
  display: flex;
  align-items: center;
}

.discount-price {
  font-size: 36rpx;
  color: #FF2442;
  font-weight: bold;
  margin-right: 20rpx;
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
}

/* 数量与总价模块 */
.quantity-total-section {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.section-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  font-size: 30rpx;
}

.section-item:not(:last-child) {
  border-bottom: 1rpx solid #f5f5f5;
}

.item-label {
  color: #666;
}

.item-value {
  color: #333;
}

.total-price {
  color: #FF2442;
  font-weight: bold;
}

/* 金币抵扣 */
.coin-deduction {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.checkbox {
  display: flex;
  align-items: center;
  font-size: 28rpx;
}

/* 底部固定菜单 */
.fixed-bottom-menu {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.price-display {
  display: flex;
  align-items: center;
}

.final-price {
  font-size: 36rpx;
  color: #FF2442;
  font-weight: bold;
  margin-right: 15rpx;
}

.original-price-line {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.pay-button {
  background: linear-gradient(to right, #FF2442, #FF6B81);
  color: #fff;
  padding: 15rpx 40rpx;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: bold;
}
.youhuiLine{
	display: flex;justify-content: space-between;
	margin-top: 20rpx;background: #fff;
	padding: 20rpx;
}
.jtImg{
	width: 12rpx;height: 20rpx;
	margin-top: 12rpx;
	    margin-left: 10rpx;
}
.coupon{
	display: flex;color: #999;
}
.detailsBox{
	margin-top: 20rpx;
	background: #fff;
   padding: 20rpx;
}
.specs{
	font-size: 26rpx;
	    color: #666;
}
.yueyueINput{
	width: 500rpx;
}
.Appointment{
	color: #6d4424;
	    border: 1px solid #6d4424;
	    border-radius: 10rpx;
	    overflow: hidden;
}
</style>